package com.bvgol.examples.netty.http;/**
 * @Classname HttpServerHandler
 * @Description TODO
 * @Date 2021/7/9 18:19
 * @Created by GUOCHEN
 */

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @program: my-spring-completely
 * @description:
 * @author: GUOCHEN
 * @create: 2021/07/09 18:19
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取客户端数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest){
            System.out.println("msg 类型: "+msg.getClass());
            System.out.println("客户端地址: "+ctx.channel().remoteAddress()+"  ---"+this.hashCode());
            System.out.println("ctx 的 类型 ： " + ctx.getClass());
            //保存全部handler信息
            System.out.println("cxt 中的pipelin ： " + ctx.pipeline());
            System.out.println("cxt 中的channel ： " + ctx.channel());
            System.out.println("cxt 中的handler ： " + ctx.handler());
            ByteBuf byteBuf = Unpooled.copiedBuffer("你好,我是服务器,请求以收到", CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,byteBuf);


            //为什么初始的时候是2次请求
            //有一个是图片的请求.网站默认图标
            HttpRequest request = (HttpRequest) msg;
            URI uri = new URI(request.uri());
            //过滤指定资源
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了 /favicon.ico ，但不做反应");
                //todo 暂时这样但是不对.会导致浏览这个请求失败
                return;
            }

            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text.plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

            //将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }
}
